﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrmField.Plugins
{
    public class ConfigurationManager
    {
        /// <summary>
        /// Retrieve all configuration records
        /// </summary>
        /// <param name="servicedAppointmentId"></param>
        /// <param name="service"></param>
        /// <returns></returns>
        public static Dictionary<string,string> RetrieveAllConfiguration(IOrganizationService service)
        {
            QueryExpression query = new QueryExpression("fsapp_configuration");
            query.ColumnSet = new ColumnSet(new String[] { "fsapp_key", "fsapp_value" });
            EntityCollection configurationCollection = service.RetrieveMultiple(query);

            Dictionary<string, string> configuration = new Dictionary<string, string>(configurationCollection.Entities.Count);

            configurationCollection.Entities.ToList().ForEach(
                (e) =>
                {
                    if (e.Contains("fsapp_key") && e["fsapp_key"] != null)
                    {

                        configuration.Add(e["fsapp_key"].ToString(),
                                          e.Contains("fsapp_value") && e["fsapp_value"] != null ?
                                          e["fsapp_value"].ToString() : string.Empty);
                    }

                }
            );

            return configuration;
        }
    }
}
